package org.yxj.requestlib.manager.api;

import android.text.TextUtils;
import android.util.Log;
import com.google.gson.Gson;
import org.yxj.requestlib.i.BaseServer;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;
import okhttp3.Authenticator;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.Route;
import retrofit2.Converter;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

public class RequestManager {

    /**
     * 实例化okHttp对象
     */
    private OkHttpClient.Builder httpClient;
    private Retrofit retrofit;
    private String ApiHOST = "" ;
    private static RequestManager manager ;


    public static RequestManager getInstance(){
        if (null==manager){
            synchronized (RequestManager.class){
                if (null==manager){
                    manager = new RequestManager();
                }
            }
        }
        return manager ;
    }



    /**
     * 初始化
     *
     * @param baseUrl  传入接口地址
     */
    public RequestManager init(String baseUrl){
        if (!TextUtils.isEmpty(baseUrl)){
            this.ApiHOST=baseUrl ;
        }
        return this;
    }




    /**
     * 授权认证
     */
//    private String authorization = "Bearer eyJhbGciOiJSUzI1NiIsImtpZCI6IjZFRDFDQkJFQzUzMzBEREVGQ0E3MUIxRUZCNzU4NTUzQTI5NkM1NzdSUzI1NiIsInR5cCI6ImF0K2p3dCIsIng1dCI6ImJ0SEx2c1V6RGQ3OHB4c2UtM1dGVTZLV3hYYyJ9.eyJuYmYiOjE2NDEzNzQwNzYsImV4cCI6MTY0MTM3NzY3NiwiaXNzIjoiaHR0cDovLzQ3LjEwMi40Ny40Ojg2MDEiLCJhdWQiOlsiQXV0b1RyYWNrX0FwaSIsIlRhZ19BcGkiLCJXZUJvX0FkbWluQXBpIiwiV2VCb19BcGkiXSwiY2xpZW50X2lkIjoiV2VCb19BcGlfQ2xpZW50Iiwic3ViIjoiMTQ2MTI1NzI0MzM4MTk5MzQ3MiIsImF1dGhfdGltZSI6MTY0MTM3NDA3NiwiaWRwIjoibG9jYWwiLCJVc2VySWQiOiIxNDYxMjU3MjQzMzgxOTkzNDcyIiwiVXNlck5hbWUiOiJtd3QiLCJBZG1pblJvbGVJZCI6IjEiLCJMb2dpbklkIjoiMTQ3ODY1NjE2NTU4NjkzMTcxMiIsIklwIjoiMjIwLjExMi4yNDIuMTE0IiwiU2Vzc2lvbktleSI6IiIsImp0aSI6IkM3Q0QxRUM5NUFDM0Q1QTNFQ0ZEMjRBQUFFM0M1MDg5IiwiaWF0IjoxNjQxMzc0MDc2LCJzY29wZSI6WyJBdXRvVHJhY2tfQXBpIiwib3BlbmlkIiwicHJvZmlsZSIsIlRhZ19BcGkiLCJXZUJvX0FkbWluQXBpIiwiV2VCb19BcGkiLCJvZmZsaW5lX2FjY2VzcyJdLCJhbXIiOlsiV2VCb19Mb2dpbl9CeV9QYXNzd29yZCJdfQ.Zd7TaHCCAskp8UDUI1ODYu5iXpckW1VXyFu1-jlEFdh7dgoUxSrLyrrWUhKF2AwnNilZyMG84KggszxW4Ik53ZMgGU7WfZb0R5pwSzd9IBubFeniTnl8Udp7cFUYInxpIJ_APlRwUdjHmC7wzHVM_ounT1owKgq6KiWx_l0kfdBI_7nDTH8tFu15NCMPSBJcfCj8zC0c-MXulidxnT3YLVjHX99tJLU-SRFysQGn09dpuxOpLbm9svA9TeE6yaS1NBvd_6xtKmma8CEFOtnFygngC9hwnXaDJdfiI2veryesYO5Jed4brBouSef794A0OuS4gi7-JCvKp86t04Sa8w" ;
    private String authorization = "";
    public RequestManager setAuthorization(final String authorization){
        this.authorization = authorization;
        return RequestManager.this;
    }



    /**
     * @param serviceClass
     * @param <S>
     * @return
     */
    private synchronized <S> S createService(Class<S> serviceClass) {

        httpClient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.MINUTES)
                .readTimeout(20, TimeUnit.MINUTES)
                .addInterceptor(new MyHttpLoggingInterceptor().loggingInterceptor)
                .authenticator(new Authenticator() {
                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        return response.request()
                                .newBuilder()
                                .header("Authorization", authorization)
                                .build();
                    }
                });

        retrofit = new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(new Gson())) //上传数据转换器
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(new NullOnEmptyConverterFactory())
                .client(httpClient.build())
                .baseUrl(ApiHOST)
                .build();


        httpClient.interceptors().add(new HttpInterceptor());

        S s=retrofit.create(serviceClass);

        return s;
    }






    /**
     * @return
     */
    public synchronized <S> S req(Class<S> ... cls){
        if (cls!=null&& cls.length>0){
            return createService(cls[0]);
        }else {
            return (S) createService(BaseServer.class);
        }
    }



    private  class HttpInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request.Builder builder = chain.request().newBuilder();
            Request request = builder
//                    .addHeader("Content-type", "application/json")
//                    .addHeader("Content-type", "text/xml")
//                    .addHeader("Accept","application/json")
                    .addHeader("Authorization", authorization)
                    .build();
            Log.i("RetrofitLog","Authorization = "+authorization);
            return chain.proceed(request);
        }
    }






    static class NullOnEmptyConverterFactory extends Converter.Factory {

        @Override
        public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

            final Converter<ResponseBody, ?> delegate =
                    retrofit.nextResponseBodyConverter(this, type, annotations);
            return new Converter<ResponseBody,Object>() {
                @Override
                public Object convert(ResponseBody body) throws IOException {
                    if (body.contentLength() == 0)
                        return null;
                    return delegate.convert(body);
                }
            };
        }
    }
}
